package com.doubletick.proxy.ipidea.util;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.doubletick.common.exception.ServiceException;
import com.doubletick.proxy.ipidea.util.dto.BaseDto;
import com.doubletick.proxy.ipidea.util.dto.IpIdeaResponseDto;
import com.doubletick.proxy.ipidea.util.dto.flow.FlowLeft;
import com.doubletick.proxy.ipidea.util.dto.flow.FlowQueryProxyAccountUseRecord;
import com.doubletick.proxy.ipidea.util.dto.flow.FlowQueryUseRecord;
import com.doubletick.proxy.ipidea.util.dto.flow.FlowUserRecord;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.math.BigDecimal;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 流量相关
 */
@Slf4j
public class ProxyFlowUtil {

    static BigDecimal flowSum = new BigDecimal("0");

    @SneakyThrows
    public static void main(String[] args) {
//        FlowLeft flowLeft = flowLeft();
//        log.info("剩余流量:{}M {}G", flowLeft.getFlow_left(), flowLeft.getFlow_left().divide(new BigDecimal("1024"),16, RoundingMode.HALF_UP));

//        查询主账号
//        useRecord();

        //查看认证账户流量
        String proxyId = "737702"; // ipidea_june_h5
        proxyId = "154003"; // ipidea_june
        proxyId = "741772"; // demf_8533
        List<FlowUserRecord> list = proxyAccountUseRecordOld(proxyId);

        list.forEach(record -> {
            String  filterDate= "2024-07-17";
            String dateTime = DateUtil.formatDateTime(new Date(Integer.parseInt(record.getDay()) * 1000L));
            if(dateTime.contains(filterDate) && new BigDecimal(record.getGlobal()).compareTo(BigDecimal.ZERO) != 0){
                log.info("rec:{}:{}:{}", dateTime,record.getGlobal(), JSON.toJSONString(record));
            }
            if (dateTime.startsWith(filterDate)) {
                log.info("rec:{}:{}", dateTime, JSON.toJSONString(record));
                flowSum = flowSum.add(new BigDecimal(record.getGlobal()));
            }
        });
        System.out.println("总流量:" + flowSum);
//        String ss = "[{\"day\":\"1720022400\",\"global\":1393.36,\"last_flow\":0},{\"day\":\"1720026000\",\"global\":1467.01,\"last_flow\":0},{\"day\":\"1720029600\",\"global\":1337.57,\"last_flow\":0},{\"day\":\"1720033200\",\"global\":1197.96,\"last_flow\":0},{\"day\":\"1720036800\",\"global\":1198.69,\"last_flow\":0},{\"day\":\"1720040400\",\"global\":1048.31,\"last_flow\":0},{\"day\":\"1720044000\",\"global\":1091.19,\"last_flow\":0},{\"day\":\"1720047600\",\"global\":993.62,\"last_flow\":0},{\"day\":\"1720051200\",\"global\":1160.03,\"last_flow\":0},{\"day\":\"1720054800\",\"global\":1129.08,\"last_flow\":0},{\"day\":\"1720058400\",\"global\":1094.33,\"last_flow\":0},{\"day\":\"1720062000\",\"global\":1000.71,\"last_flow\":0},{\"day\":\"1720065600\",\"global\":917.51,\"last_flow\":0},{\"day\":\"1720069200\",\"global\":987.08,\"last_flow\":0},{\"day\":\"1720072800\",\"global\":1120.21,\"last_flow\":0},{\"day\":\"1720076400\",\"global\":1211.4,\"last_flow\":0},{\"day\":\"1720080000\",\"global\":1318.58,\"last_flow\":0},{\"day\":\"1720083600\",\"global\":1436.04,\"last_flow\":0},{\"day\":\"1720087200\",\"global\":0,\"last_flow\":0},{\"day\":\"1720090800\",\"global\":0,\"last_flow\":0},{\"day\":\"1720094400\",\"global\":0,\"last_flow\":0},{\"day\":\"1720098000\",\"global\":0,\"last_flow\":0},{\"day\":\"1720101600\",\"global\":0,\"last_flow\":0},{\"day\":\"1720105200\",\"global\":0,\"last_flow\":0}]";
//            ss="[{\"day\":\"1720022400\",\"global\":1393.36,\"last_flow\":0},{\"day\":\"1720026000\",\"global\":1467.01,\"last_flow\":0},{\"day\":\"1720029600\",\"global\":1337.57,\"last_flow\":0},{\"day\":\"1720033200\",\"global\":1197.96,\"last_flow\":0},{\"day\":\"1720036800\",\"global\":1198.69,\"last_flow\":0},{\"day\":\"1720040400\",\"global\":1048.31,\"last_flow\":0},{\"day\":\"1720044000\",\"global\":1091.19,\"last_flow\":0},{\"day\":\"1720047600\",\"global\":993.62,\"last_flow\":0},{\"day\":\"1720051200\",\"global\":1160.03,\"last_flow\":0},{\"day\":\"1720054800\",\"global\":1129.08,\"last_flow\":0},{\"day\":\"1720058400\",\"global\":1094.33,\"last_flow\":0},{\"day\":\"1720062000\",\"global\":1000.71,\"last_flow\":0},{\"day\":\"1720065600\",\"global\":917.51,\"last_flow\":0},{\"day\":\"1720069200\",\"global\":987.08,\"last_flow\":0},{\"day\":\"1720072800\",\"global\":1120.21,\"last_flow\":0},{\"day\":\"1720076400\",\"global\":1211.4,\"last_flow\":0},{\"day\":\"1720080000\",\"global\":1318.58,\"last_flow\":0},{\"day\":\"1720083600\",\"global\":1436.04,\"last_flow\":0},{\"day\":\"1720087200\",\"global\":0,\"last_flow\":0},{\"day\":\"1720090800\",\"global\":0,\"last_flow\":0},{\"day\":\"1720094400\",\"global\":0,\"last_flow\":0},{\"day\":\"1720098000\",\"global\":0,\"last_flow\":0},{\"day\":\"1720101600\",\"global\":0,\"last_flow\":0},{\"day\":\"1720105200\",\"global\":0,\"last_flow\":0}]";
//        JSONArray array = JSONArray.parseArray(ss);
//        for (int i = 0; i < array.size(); i++) {
//            FlowUserRecord record = array.getObject(i, FlowUserRecord.class);
//            String dateTime = DateUtil.formatDateTime(new Date(Integer.parseInt(record.getDay()) * 1000L));
//            log.info("rec:{}:{}",dateTime , JSON.toJSONString(record));
//        }

    }

    /**
     * 获取剩余流量 (可以做预警)
     */
    private static FlowLeft flowLeft() {
        String url = IpIdeaConstant.BASE_URL + "/flow_left";
        IpIdeaResponseDto dto = IpIdeaUtil.request(url, new BaseDto(), "获取剩余流量");
        if (!dto.isSuccess()) {
            throw new ServiceException(dto.getCode() + ":" + dto.getMsg());
        }
        return JSON.to(FlowLeft.class, dto.getRet_data());
//        {"ret":0,"code":"1","msg":"success","ret_data":{"flow_left":4994439.622761},"timestamp":1720087471}
//        {"ret":0,"code":"1","msg":"success","ret_data":{"flow_left":4994425.139386},"timestamp":1720087551}
    }


    //1720072800
//1720076400
    static String regex = "\\d+";
    static Pattern pattern = Pattern.compile(regex);


    /**
     * 不传时间戳，返回的day 是  1720072800  这种10位数字，返回的是当天的数据，包括0-23点
     * setIs_hour  只有在传了时间戳才会生效
     * TODO  必须传 id 和时间戳才正常 ,按天统计有问题
     *
     * @return
     */
    @SneakyThrows
    public static List<FlowUserRecord> proxyAccountUseRecord(int days, String proxyId) {
        String url = IpIdeaConstant.BASE_URL + "/flow_proxy_account_use_record";
        FlowQueryProxyAccountUseRecord queryUseRecord = new FlowQueryProxyAccountUseRecord();
        queryUseRecord.setIs_hour(Boolean.TRUE.toString());
        queryUseRecord.setId(proxyId);
        queryUseRecord.setStart_time("" + ((System.currentTimeMillis() - 1000L * 60 * 60 * 24 * days) / 1000));
        queryUseRecord.setEnd_time("" + ((System.currentTimeMillis()) / 1000));
        IpIdeaResponseDto dto = null;
        int errorCount = 0;
        while (true) {
            dto = IpIdeaUtil.request(url, queryUseRecord, "查看认证账户流量");
            if (dto.isSuccess()) {
                break;
            }
            String msg = dto.getMsg();
            Matcher matcher = pattern.matcher(msg);
            if (msg.contains("秒后再次请求") && matcher.find() && errorCount++ < 3) {
                Long sleep = Integer.parseInt(matcher.group()) * 1000L + 100;
                log.info("重试:{}:{}", errorCount, sleep);
                Thread.sleep(sleep);
            } else {
                throw new ServiceException(dto.getCode() + ":" + dto.getMsg());
            }
        }
        Object o = dto.getRet_data();
        List<FlowUserRecord> list = new ArrayList<>();
        if (o instanceof JSONArray) {
            JSONArray array = (JSONArray) o;
            for (int i = 0, len = array.size(); i < len; i++) {
                list.add(array.getObject(i, FlowUserRecord.class));
            }
        }
//        Map<String, BigDecimal> countMap = new HashMap<>();
//        for (FlowUserRecord flowUserRecord : list) {
//            Long millis;
//            if (NumberUtil.isLong(flowUserRecord.getDay()) && flowUserRecord.getDay().length() != 10) {
//                millis = Long.parseLong(flowUserRecord.getDay());
//            } else {
//                millis = Integer.parseInt(flowUserRecord.getDay()) * 1000L;
//            }
//            String dateTime = DateUtil.formatDateTime(new Date(millis));
//            log.info("{}:{}:{}", dateTime, flowUserRecord.getGlobal(), JSON.toJSONString(flowUserRecord));
//            String date = dateTime.substring(0, 10);
//            if (!countMap.containsKey(date)) {
//                countMap.put(date, new BigDecimal(0));
//            }
//            BigDecimal b = countMap.get(date).add(new BigDecimal(flowUserRecord.getGlobal()));
//            countMap.put(date, b);
//        }
//        countMap.forEach((k, v) -> {
//            log.info("k:{} v:{}", k, v);
//        });
        return list;
    }

    /**
     * 不传时间戳，返回的day 是  1720072800  这种10位数字，返回的是当天的数据，包括0-23点
     * setIs_hour  只有在传了时间戳才会生效
     * TODO  必须传 id 和时间戳才正常 ,按天统计有问题
     *
     * @return
     */
    public static List<FlowUserRecord> proxyAccountUseRecordOld(String proxyId) {
        String url = IpIdeaConstant.BASE_URL + "/flow_proxy_account_use_record";
        FlowQueryProxyAccountUseRecord queryUseRecord = new FlowQueryProxyAccountUseRecord();
        queryUseRecord.setIs_hour(Boolean.TRUE.toString());
        queryUseRecord.setId(proxyId);
        queryUseRecord.setStart_time("" + ((System.currentTimeMillis() - 1000L * 60 * 60 * 24 *  1) / 1000));
        queryUseRecord.setEnd_time("" + ((System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 0) / 1000));
        IpIdeaResponseDto dto = IpIdeaUtil.request(url, queryUseRecord, "查看认证账户流量");
        if (!dto.isSuccess()) {
            throw new ServiceException(dto.getCode() + ":" + dto.getMsg());
        }
//        1656518400
        Object o = dto.getRet_data();
        List<FlowUserRecord> list = new ArrayList<>();
        if (o instanceof JSONArray) {
            JSONArray array = (JSONArray) o;
            for (int i = 0, len = array.size(); i < len; i++) {
                list.add(array.getObject(i, FlowUserRecord.class));
            }
        }
        Map<String, BigDecimal> countMap = new HashMap<>();

        for (FlowUserRecord flowUserRecord : list) {
            Long millis;
            if (NumberUtil.isLong(flowUserRecord.getDay()) && flowUserRecord.getDay().length() != 10) {
                millis = Long.parseLong(flowUserRecord.getDay());
            } else {
                millis = Integer.parseInt(flowUserRecord.getDay()) * 1000L;
            }
            String dateTime = DateUtil.formatDateTime(new Date(millis));
//            if (!Objects.equals(flowUserRecord.getGlobal(), "0")) {
            log.info("{}:{}:{}", dateTime, flowUserRecord.getGlobal(), JSON.toJSONString(flowUserRecord));
            String date = dateTime.substring(0, 10);
            if (!countMap.containsKey(date)) {
                countMap.put(date, new BigDecimal(0));
            }
            BigDecimal b = countMap.get(date).add(new BigDecimal(flowUserRecord.getGlobal()));
            countMap.put(date, b);
//            }
        }

        //
        countMap.forEach((k, v) -> {
            log.info("k:{} v:{}", k, v);
        });

        System.out.println("list:" + list.size());
        return list;
    }

    /**
     * 查看主账户流量使用   ----------无用
     *
     * @return
     */
    public static Object useRecord() {
        String url = IpIdeaConstant.BASE_URL + "/flow_use_record";
        FlowQueryUseRecord queryUseRecord = new FlowQueryUseRecord();
        queryUseRecord.setStart_time("" + (System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 7));
        queryUseRecord.setEnd_time("" + (System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 0));
        return IpIdeaUtil.request(url, queryUseRecord, "查看主账户流量使用");
    }


//     <!-- 根据主键尝试插入，如果存在则更新 -->
//    <insert id="upsertUser" parameterType="com.example.model.User">
//    INSERT INTO users (id, department_id, name, email, age, created_time, last_modified_time)
//    VALUES (#{id}, #{departmentId}, #{name}, #{email}, #{age}, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
//    ON DUPLICATE KEY UPDATE
//    name = VALUES(name),
//    email = VALUES(email),
//    age = VALUES(age),
//    last_modified_time = CURRENT_TIMESTAMP
//   </insert>
//
}
